class Utils {
	constructor() {
		// this.baseUrl = 'http://47.98.201.46:18080';
		this.baseUrl = 'http://192.168.1.160:18080';
	}

	myrequest(options = { myloading: false }) {
		if (!options.myurl) {
			console.error('请求错误：缺少URL');
			return;
		}

		if (options.myloading) {
			this.showmyLoading();
			uni.setStorageSync('ifloading', true); // 标记正在加载
		}

		uni.request({
			url: this.baseUrl + options.myurl,
			data: options.data || {},
			header: options.header || {},
			method: options.method || 'GET', // 默认为GET方法
			success: res => {
				uni.hideLoading();
				uni.setStorageSync('ifloading', false);

				if (res.statusCode !== 200 || res.data.code !== 200) {
					if (options.myfail && typeof options.myfail === 'function') {
						options.myfail(res);
					}
					return;
				}

				if (options.mysuccess && typeof options.mysuccess === 'function') {
					options.mysuccess(res.data);
				}
			},
			fail: err => {
				if (options.myfail && typeof options.myfail === 'function') {
					options.myfail(err);
				}
				uni.hideLoading();
				uni.setStorageSync('ifloading', false);
			}
		});
	}

	showmyLoading() {
		const isAlreadyLoading = uni.getStorageSync('ifloading');

		if (isAlreadyLoading) {
			uni.hideLoading();
		}

		uni.showLoading({
			title: '正在努力加载中...',
		});

		uni.setStorageSync('ifloading', true);
	}
}

export async function getUserInfoFromUserTap() {
	try {
		const userProfile = await new Promise((resolve, reject) => {
			uni.getUserProfile({
				desc: '用于完善会员资料', // 必填，使用场景说明
				success: resolve,
				fail: reject
			});
		});

		// 调用微信登录接口获取code
		const loginRes = await new Promise((resolve, reject) => {
			uni.login({
				success: resolve,
				fail: reject
			});
		});

		// 将code和用户详细信息合并后发送到服务器
		const res = await new Promise((resolve, reject) => {
			myrequest({
				myurl: '/login', // 确保传递了 myurl 参数
				data: {
					code: loginRes.code,
					avatarurl: userProfile.userInfo.avatarUrl, // 注意大小写
					gender: userProfile.userInfo.gender,
					nickname: userProfile.userInfo.nickName, // 注意大小写
					telnum: userProfile.userInfo.telnum || '' // 如果有电话号码则传递，否则为空字符串
				},
				method: 'POST',
				header: {
					'Source-Platform': 'mini-program'
				},
				mysuccess: resolve,
				myfail: reject
			});
		});

		const userInfo = res.data;
		userInfo.timestamp = Date.now(); // 添加时间戳

		console.log('成功获取数据', userInfo);

		// 存储用户信息到本地缓存
		uni.setStorageSync('userInfo', userInfo);
		uni.setStorageSync('token', userInfo.token);

		return userInfo;
	} catch (error) {
		console.error('登录或获取用户信息失败', error);
		uni.showToast({
			title: '登录失败，请重试！',
			icon: 'none'
		});
		throw error;
	}
}

export function myrequest(options = {
	myloading: false
}) {
	const utilsInstance = new Utils();
	return utilsInstance.myrequest(options);
}

const utilsInstance = new Utils();
export default utilsInstance;